//
//  AudioStream.cpp
//  FilterModule_Standalone
//
//  Created by kadlubek47 on 21.08.2013.
//  Copyright (c) 2013 kadlubek47. All rights reserved.
//

#include "AudioStream.h"


#pragma mark Construct, destroy

AudioStream::AudioStream (std::string fileName, unsigned int blockSize) {
    channels_blocks_.channelLength_ = blockSize;
    
    //Read file..
    IAudioFileIOManager::IAudioFileIOManager_struct str;
    str.wantedBytePerSample = sizeof(float_type);
    fileIOManager_.read( (void**)(&channels_.in_.data_), fileName.c_str(), str );
    //.
    
    //Initialize channels_, channels_blocks_
    //Assignments
    numOfBlocks_                    = (unsigned int) (str.channelLength / (long long) blockSize);
    channels_.numOfChannels_        = channels_blocks_.numOfChannels_ = str.numOfChannels;
    channels_.channelLength_        = (unsigned int) str.channelLength;
    sampleRate_ = str.sampleRate;
    //.
    
    //Create buffers
    channels_.out_         = new float_type [       channels_.channelLength_ *        channels_.numOfChannels_];
    channels_blocks_.in_   = new float_type [channels_blocks_.channelLength_ * channels_blocks_.numOfChannels_];
    channels_blocks_.out_  = new float_type [channels_blocks_.channelLength_ * channels_blocks_.numOfChannels_];
    //.
    //.
    
    //prepare first block
    for(unsigned int channNum = 0; channNum < channels_blocks_.numOfChannels_; ++channNum)
        for(unsigned int sampleNum = 0; sampleNum < channels_blocks_.channelLength_; ++sampleNum)
            channels_blocks_.in_[channNum][sampleNum] = channels_.in_[channNum][sampleNum + i_block_*channels_blocks_.channelLength_];
    //.
}

AudioStream::~AudioStream() {}



#pragma mark Actions

bool AudioStream::nextBlock() {
    if(numOfBlocks_ == 0 || i_block_ == numOfBlocks_)
        return false;
    
    //read
    for(unsigned int channNum = 0; channNum < channels_blocks_.numOfChannels_; ++channNum)
        for(unsigned int sampleNum = 0; sampleNum < channels_blocks_.channelLength_; ++sampleNum)
            channels_.out_[channNum][sampleNum + i_block_*channels_blocks_.channelLength_] = channels_blocks_.out_[channNum][sampleNum];
    //.
    
    ++i_block_;
    if(i_block_ == numOfBlocks_)
        return false;
    
    //write into block_channelsIn next block;
    for(unsigned int channNum = 0; channNum < channels_blocks_.numOfChannels_; ++channNum)
        for(unsigned int sampleNum = 0; sampleNum < channels_blocks_.channelLength_; ++sampleNum)
            channels_blocks_.in_[channNum][sampleNum] = channels_.in_[channNum][sampleNum + i_block_ * channels_blocks_.channelLength_];
    
    return true;
}

void AudioStream::close(std::string fileName) {
    fileIOManager_.write( (void*)channels_.out_.data_, fileName.c_str() );
}